/**
* All Rights Reserved , Copyright (C) 2022 , 青岛鼎信通讯股份有限公司
*
* MpmProjectSquaredService
* 销售项目九宫格
*
* 修改纪录
* 2022-11-09 版本：1.0 houyuhang 创建。
* @version 版本：1.0
* @author 作者：houyuhang
* 创建日期：2022-11-09
*/
package com.topscomm.mpm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.mpm.pojo.MpmProjectSquaredEntity;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.mpm.service.IMpmProjectSquaredService;
import com.topscomm.mpm.service.impl.auto.MpmProjectSquaredServiceAuto;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;

@Service(value = "mpmProjectSquaredService")
@Scope(value = "singleton")
public class MpmProjectSquaredService extends MpmProjectSquaredServiceAuto implements IMpmProjectSquaredService {
    /**
     * @author: houyuhang
     * @date: 2022-11-09
     * @param paraMap
     * @return
     * @description:保存九宫格信息
     * @modify:
     */
    @Transactional
    public void doSaveSquared(Map<String, Object> paraMap) {
        List<Map<String, Object>> squaredList = (List<Map<String, Object>>) paraMap.get("data");
        if (CollectionUtil.isEmpty(squaredList)) {
            throw new ServiceException("请填写客户关系内容！");
        }
        // 获取历史客户关系内容
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" enabled = 1 and taskid = '{0}' order by version desc ", ConvertUtil.convertToString(squaredList.get(0).get("taskid")));
        List<MpmProjectSquaredEntity> mpmProjectSquaredEntities = this.queryByWhere(sql.toString());
        long version = 0L;
        if (!CollectionUtil.isEmpty(mpmProjectSquaredEntities)) {
            version = mpmProjectSquaredEntities.get(0).getVersion() + 1;
        }
        // 如果任务还没有下发（即任务在策划页面填写），删除历史记录（不记录九宫格修改历史）
        if (paraMap.containsKey("qry_state") && !"9".equals(ConvertUtil.convertToString(paraMap.get("qry_state")))) {
            sql.clear();
            sql.appendSingle(" enabled = 1 and taskid = '{0}' ", ConvertUtil.convertToString(squaredList.get(0).get("taskid")));
            this.deleteByWhere(sql.toString());
            version = 0L;
        }
        // 新增客户关系信息
        List<BasicEntity> basicEntities = new ArrayList<>();
        for (Map<String, Object> squaredMap : squaredList) {
            MpmProjectSquaredEntity mpmProjectSquaredEntity = new MpmProjectSquaredEntity();
            squaredMap.put("id", 0L);
            squaredMap.put("version", version);
            basicEntities.add(mpmProjectSquaredEntity.convertFromMap(squaredMap));
        }
        this.insertBatch(basicEntities);
    }
    /**
     * @author: houyuhang
     * @date: 2022-11-14
     * @return
     * @description:九宫格数据获取
     * @modify:
     */
    @Transactional
    public Map<String, Object> querySquaredInfo(Map<String, Object> paraMap) {
        // 获取该任务历次分数数据
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" enabled = 1 and taskid = '{0}' ", paraMap.get("taskid"));
        List<Map<String, Object>> squaredList = this.queryMapByWhere(sql.toString(), "querySquaredInfo");
        if (CollectionUtil.isEmpty(squaredList)) {
            Map<String, Object> emptyMap = new HashMap<>();
            emptyMap.put("datalist", new ArrayList<>());
            emptyMap.put("userrole", "");
            return emptyMap;
        }
        Map<String, List<Map<String, Object>>> squaredMap = squaredList.stream().collect(Collectors.groupingBy(item -> ConvertUtil.convertToString(item.get("userrole"))));
        List<Map<String, Object>> sList = new ArrayList<>();
        StringBuffer stringBuffer = new StringBuffer();
        // 获取角色顺序信息，现在存在的角色在前，其余角色放在后面
        sql.clear();
        sql.appendSingle(" taskid = '{0}' and version = (select max(version) from mpmprojectsquared where taskid = '{0}') ", paraMap.get("taskid"));
        List<MpmProjectSquaredEntity> sortEntity = this.queryByWhere(sql.toString());
        List<String> copySortList = new ArrayList<>(squaredMap.keySet());
        List<String> sortStrList = new ArrayList<>();
        for (MpmProjectSquaredEntity tempEntity : sortEntity) {
            sortStrList.add(tempEntity.getUserrole());
            copySortList.remove(tempEntity.getUserrole());
        }
        sortStrList.addAll(copySortList);
        // 遍历获取角色和角色得分信息
        for(String key : sortStrList) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("name", key);
            List<Object> dataList = new ArrayList<>();
            for (Map<String, Object> tempMap : squaredMap.get(key)) {
                List<Double> countList = new ArrayList<>();
                countList.add(ConvertUtil.convertToDouble(tempMap.get("friendship")));
                countList.add(ConvertUtil.convertToDouble(tempMap.get("business")));
                dataList.add(countList);
            }
            dataMap.put("data", dataList);
            sList.add(dataMap);
            stringBuffer.append(key + ",");
        }
        Map<String, Object> resultMap = new HashMap<>();
        String str = stringBuffer.toString();
        resultMap.put("userrole", str.substring(0, str.length() - 1));
        resultMap.put("datalist", sList);
        return resultMap;
    }
}
